<template>
  <div class="shoppingCart" :class="{ 'light-theme': $store.state.theme === 'light' }">
    <div class="cartList" v-if="cartValid.length">
      <div class="header acea-row row-middle">
        <div class="allSelect acea-row row-center-wrapper" @click="allChecked">
          <label class="well-check">
            <input type="checkbox" name="" value="" :checked="isAllSelect" @click="allChecked" />
            <i class="icon"></i>
            <span class="checkAll">全選</span>
          </label>
        </div>
        <div class="info acea-row row-center-wrapper">商品信息</div>
        <div class="price acea-row row-center-wrapper">单價</div>
        <div class="num acea-row row-center-wrapper">数量</div>
        <div class="money acea-row row-center-wrapper">金額</div>
        <div class="operate acea-row row-center-wrapper">操作</div>
      </div>
      <div class="body">
        <div class="item acea-row row-middle" v-for="(item, index) in cartValid" :key="index">
          <div class="allSelect acea-row row-center-wrapper">
            <label class="well-check">
              <input type="checkbox" name="" value="" :checked="item.checked" @click="switchSelect(index)" />
              <i class="icon"></i>
            </label>
          </div>
          <div class="info acea-row row-middle">
            <div class="pictrue">
              <img v-if="item.productInfo.attrInfo" :src="item.productInfo.attrInfo.image" />
              <img v-else :src="item.productInfo.image" />
            </div>
            <div class="text">
              <div class="name line2">{{ item.productInfo.store_name }}</div>
              <div class="infor" v-if="item.productInfo.attrInfo">
                属性：{{ item.productInfo.attrInfo.suk }}
              </div>
            </div>
          </div>
          <div class="price acea-row row-center-wrapper">
            ${{ item.truePrice }}
          </div>
          <div class="num acea-row row-center-wrapper">
            <div class="iconfont icon-minus" :class="item.cart_num <= 1 ? 'grey' : ''" @click.prevent="reduce(index)">
            </div>
            <!--<div class="numCon">{{item.cart_num}}</div>-->
            <input class="numCon" v-model="item.cart_num" @input="inputNum(item)" />
            <button :disabled="item.cart_num >= item.trueStock" class="iconfont icon-add"
              :class="item.cart_num >= item.trueStock ? 'grey' : ''" @click.prevent="plus(index)"></button>
          </div>
          <div class="money acea-row row-center-wrapper font-color">
            ${{ comsys.Mul(item.truePrice, item.cart_num) }}
          </div>
          <div class="operate acea-row row-center-wrapper" @click="delgoods(item)">
            <span class="iconfont icon-ashbin"></span>
          </div>
        </div>
      </div>
    </div>
    <div class="cartList invalid" v-if="cartInvalid.length">
      <div class="body">
        <div class="item acea-row row-middle" v-for="(item, index) in cartInvalid" :key="index">
          <div class="allSelect"></div>
          <div class="info acea-row row-center-wrapper">
            <div class="pictrue">
              <img :src="item.productInfo.attrInfo.image" v-if="item.productInfo.attrInfo" />
              <img :src="item.productInfo.image" v-else />
            </div>
            <div class="text">
              <div class="name line2 grey">
                {{ item.productInfo.store_name }}
              </div>
              <div class="infor" v-if="item.productInfo.attrInfo">
                属性：{{ item.productInfo.attrInfo.suk }}
              </div>
            </div>
          </div>
          <div class="price acea-row row-center-wrapper grey">
            ${{ item.truePrice }}
          </div>
          <div class="num acea-row row-center-wrapper">
            <div class="iconfont icon-minus grey"></div>
            <div class="numCon grey">{{ item.cart_num }}</div>
            <div class="iconfont icon-add grey"></div>
          </div>
          <div class="money acea-row row-center-wrapper font-color grey">
            ${{ comsys.Mul(item.truePrice, item.cart_num) }}
          </div>
          <div class="operate acea-row row-center-wrapper" @click="delgoods(item)">
            <span class="iconfont icon-ashbin"></span>
          </div>
        </div>
      </div>
    </div>
    <div class="footer acea-row row-between-wrapper" v-if="cartValid.length || cartInvalid.length">
      <div class="num">已選 {{ checkedIds.length }} 件商品</div>
      <div class="acea-row row-middle">
        <div class="total">
          合計：<span class="font-color">HK${{ countmoney }}</span>
        </div>
        <div class="bnt bg-color" @click="subOrder">去結算</div>
      </div>
    </div>
    <div class="noCart" v-if="!cartValid.length && !cartInvalid.length">
      <div class="pictrue"><img src="../assets/images/noCart1.png" /></div>
      <div class="tip">親，購物車还是空的哟~</div>
      <nuxt-link to="/" class="goIndex">继续逛</nuxt-link>
    </div>
  </div>
</template>

<script>
const CHECKED_IDS = "cart_checked";
export default {
  name: "shoppingCart",
  auth: "guest",
  data() {
    return {
      cartValid: [],
      cartInvalid: [],
      isAllSelect: false,
      checkedIds: [],
      countmoney: 0 //購物車產品總價；
    };
  },
  async asyncData({ app }) { },
  fetch({ store }) {
    store.commit("isHeader", true);
    store.commit("isFooter", true);
  },

  mounted() {
    document.body.setAttribute("style", "background:#ffffff");
    // 获取headers组件实例并设置滚动状态
    this.updateHeaderStyle();
    window.addEventListener('scroll', this.handleScroll);
  },

  beforeDestroy() {
    document.body.removeAttribute("style");
    window.removeEventListener('scroll', this.handleScroll);
  },
  head() {
    return {
      title: "購物車-" + this.$store.state.titleCon
    };
  },
  created() {
    this.getCartList();
  },
  mounted() {
    document.body.setAttribute("style", "background:#ffffff");
  },
  beforeDestroy() {
    document.body.removeAttribute("style");
  },
  methods: {
    inputNum(item) {
      let that = this;
      item.cart_num =
        parseInt(item.cart_num) >= item.trueStock
          ? item.trueStock
          : item.cart_num;
      item.cart_num =
        parseInt(item.cart_num) <= 1 || isNaN(parseInt(item.cart_num))
          ? 1
          : item.cart_num;
      that.countMoney();
      let conNum = 0;
      that.cartValid.forEach(i => {
        conNum += parseInt(i.cart_num);
      });
      that.cartInvalid.forEach(i => {
        conNum += parseInt(i.cart_num);
      });
      that.$store.commit("cartNum", conNum);
      that.syncCartNum(item);
    },
    //立即下单；
    subOrder: function () {
      let that = this,
        list = that.cartValid,
        id = [];
      list.forEach(function (val) {
        if (val.checked === true) {
          id.push(val.id);
        }
      });
      if (id.length === 0) {
        that.$message.error("请選擇產品");
        return;
      }
      this.$router.push({
        path: "/order_confirm",
        query: { cartId: id.join(",") }
      });
    },
    //删除商品；
    delgoods: function (item) {
      let that = this;
      let checkedIds = that.$cookies.get(CHECKED_IDS) || [];
      let index = checkedIds.indexOf(item.id);
      if (index > -1) {
        checkedIds.splice(index, 1);
      }
      that.$cookies.set(CHECKED_IDS, checkedIds);
      that.$axios.post("/cart/del", { ids: item.id.toString() }).then(res => {
        that.$message.success("删除成功");
        that.$store.commit(
          "cartNum",
          that.$store.state.cartnumber - item.cart_num
        );
        this.checkedIds = checkedIds;
        that.getCartList();
        that.countMoney();
      });
    },
    getCartList() {
      let that = this;
      that.$axios.get("/pc/get_cart_list").then(res => {
        that.cartValid = res.data.valid;
        that.cartInvalid = res.data.invalid;
        let checkedIds = that.$cookies.get(CHECKED_IDS) || [];
        if (!Array.isArray(checkedIds)) checkedIds = [];
        that.cartValid.forEach(cart => {
          if (checkedIds.length) {
            if (checkedIds.indexOf(cart.id) !== -1) cart.checked = true;
            else cart.checked = false;
          } else {
            cart.checked = true;
            that.checkedIds.push(cart.id);
          }
        });
        if (checkedIds.length) {
          that.checkedIds = checkedIds;
        }
        that.isAllSelect = that.checkedIds.length === that.cartValid.length;
        that.countMoney();
      });
    },
    //加
    plus: function (index) {
      let that = this;
      let list = that.cartValid[index];
      list.cart_num++;
      if (list.cart_num >= list.trueStock) {
        that.$set(list, "cart_num", list.trueStock);
      }
      // 重新計算購物車總數量
      let totalNum = 0;
      that.cartValid.forEach(item => {
        totalNum += parseInt(item.cart_num || 0);
      });
      that.cartInvalid.forEach(item => {
        totalNum += parseInt(item.cart_num || 0);
      });
      that.$store.commit("cartNum", totalNum);
      that.countMoney();
      that.syncCartNum(list);
    },
    //减
    reduce: function (index) {
      let that = this;
      let list = that.cartValid[index];
      list.cart_num--;
      if (list.cart_num < 1) {
        that.$set(list, "cart_num", 1);
      }

      // 重新計算購物車總數量
      let totalNum = 0;
      that.cartValid.forEach(item => {
        totalNum += parseInt(item.cart_num || 0);
      });
      that.cartInvalid.forEach(item => {
        totalNum += parseInt(item.cart_num || 0);
      });
      that.$store.commit("cartNum", totalNum);
      that.countMoney();
      that.syncCartNum(list);
    },
    syncCartNum(cart) {
      if (!cart.sync)
        cart.sync = window.debounce(() => {
          this.$axios.post("/cart/num", {
            id: cart.id,
            number: Math.max(cart.cart_num, 1) || 1
          });
        }, 500);
      cart.sync();
    },
    //单選
    switchSelect: function (index) {
      let that = this,
        cart = that.cartValid[index],
        i = this.checkedIds.indexOf(cart.id);
      cart.checked = !cart.checked;

      if (i !== -1) this.checkedIds.splice(i, 1);
      if (cart.checked) {
        this.checkedIds.push(cart.id);
      }
      let len = that.cartValid.length;
      let selectnum = [];
      for (let i = 0; i < len; i++) {
        if (that.cartValid[i].checked === true) {
          selectnum.push(true);
        }
      }
      that.isAllSelect = selectnum.length === len;
      that.$set(that, "cartValid", that.cartValid);
      that.$set(that, "isAllSelect", that.isAllSelect);
      that.$cookies.set(CHECKED_IDS, that.checkedIds);
      that.countMoney();
    },
    //全選
    allChecked: function () {
      let that = this;
      let selectAllStatus = that.isAllSelect;
      selectAllStatus = !selectAllStatus;
      let checkedIds = [];
      that.cartValid.forEach(cart => {
        cart.checked = selectAllStatus;
        if (selectAllStatus) checkedIds.push(cart.id);
      });
      that.$set(that, "cartValid", that.cartValid);
      that.$set(that, "isAllSelect", selectAllStatus);
      that.checkedIds = checkedIds;
      that.$cookies.set(CHECKED_IDS, checkedIds);
      that.countMoney();
    },
    //總共價钱；
    countMoney: function () {
      let that = this;
      let carmoney = 0;
      let array = that.cartValid;
      for (let i = 0; i < array.length; i++) {
        if (array[i].checked === true) {
          carmoney = this.comsys.Add(
            carmoney,
            this.comsys.Mul(array[i].cart_num, array[i].truePrice)
          );
        }
      }
      that.countmoney = carmoney;
    }
  }
};
</script>

<style scoped lang="scss">
.shoppingCart {
  max-width: 1200px;
  margin: 0 auto;
  padding: 120px 60px 0;
  background: var(--bg-page);
  min-height: 100vh;
  transition: background-color var(--transition-time), color var(--transition-time);

  .noCart {
    text-align: center;
    background: var(--card-bg);
    border-radius: 8px;
    box-shadow: 0 2px 8px var(--shadow-color);
    padding: 80px 40px;
    margin: 40px auto;
    max-width: 600px;
    transition: background-color var(--transition-time), box-shadow var(--transition-time);

    .pictrue {
      width: 200px;
      height: 130px;
      margin: 0 auto 30px;

      img {
        width: 100%;
        height: 100%;
        object-fit: contain;
      }
    }

    .tip {
      font-size: 16px;
      color: var(--text-secondary);
      margin-bottom: 30px;
      line-height: 1.5;
      transition: color var(--transition-time);
    }

    .goIndex {
      display: inline-block;
      padding: 12px 32px;
      background: var(--primary-base);
      color: var(--button-text);
      border: none;
      border-radius: 4px;
      font-size: 14px;
      font-weight: 500;
      text-decoration: none;
      transition: all 0.3s ease;

      &:hover {
        background: var(--primary-light);
        transform: translateY(-1px);
        box-shadow: 0 4px 12px rgba(var(--primary-base-rgb), 0.3);
      }
    }
  }
}

.cartList {
  background: var(--card-bg);
  border-radius: 8px;
  box-shadow: 0 2px 8px var(--shadow-color);
  margin-bottom: 20px;
  overflow: hidden;
  transition: background-color var(--transition-time), box-shadow var(--transition-time);

  .header {
    height: 60px;
    border-bottom: 1px solid var(--border-color);
    font-weight: 600;
    color: var(--text-secondary);
    font-size: 14px;
    transition: border-color var(--transition-time), color var(--transition-time);
  }

  .allSelect {
    width: 120px;
    display: flex;
    align-items: center;
    justify-content: flex-start;
    height: 60px;
    padding-left: 20px;
  }

  .info {
    flex: 1;
    min-width: 300px;
    padding-left: 20px;
  }

  .price {
    width: 120px;
    font-weight: 500;
  }

  .num {
    width: 140px;
  }

  .money {
    width: 120px;
    font-weight: 600;
    color: $primary-base;
  }

  .operate {
    width: 80px;
  }

  .body {
    .item {
      padding: 20px 0;
      transition: all 0.3s ease;

      &:not(:last-child) {
        border-bottom: 1px solid var(--border-color);
      }

      &:hover {
        background: var(--bg-hover);
      }

      .info {
        display: flex;
        align-items: center;

        .pictrue {
          width: 80px;
          height: 80px;
          margin-right: 16px;
          border-radius: 2px;
          overflow: hidden;
          flex-shrink: 0;

          img {
            width: 100%;
            height: 100%;
            object-fit: cover;
          }
        }

        .text {
          flex: 1;
          min-width: 0;

          .name {
            font-size: 14px;
            color: var(--text-secondary);
            line-height: 1.4;
            margin-bottom: 8px;
            font-weight: 500;
            transition: color var(--transition-time);
          }

          .infor {
            font-size: 12px;
            color: var(--text-secondary);
            background: var(--bg-light);
            padding: 4px 8px;
            border-radius: 4px;
            display: inline-block;
            transition: background-color var(--transition-time), color var(--transition-time);
          }
        }
      }

      .price {
        font-size: 16px;
        font-weight: 600;
        color: var(--primary-base);
        transition: color var(--transition-time);
      }

      .num {
        display: flex;
        align-items: center;
        justify-content: center;

        .iconfont {
          width: 32px;
          height: 32px;
          line-height: 32px;
          border: 1px solid var(--border-color);
          text-align: center;
          color: var(--text-secondary);
          background: var(--card-bg);
          cursor: pointer;
          transition: all 0.2s ease;
          font-size: 12px;

          &:hover:not(.grey) {
            border-color: var(--primary-base);
            color: var(--primary-base);
          }

          &.grey {
            color: var(--border-color);
            cursor: not-allowed;
          }
        }

        .numCon {
          width: 60px;
          height: 32px;
          border: 1px solid var(--border-color);
          border-left: none;
          border-right: none;
          font-size: 14px;
          background: var(--card-bg);
          color: var(--text-color);
          transition: background-color var(--transition-time), color var(--transition-time), border-color var(--transition-time);
          text-align: center;
          outline: none;
        }
      }

      .money {
        font-size: 16px;
        font-weight: 600;
        color: $primary-base;
      }

      .operate {
        color: #999;
        cursor: pointer;
        transition: color 0.2s ease;

        &:hover {
          color: $primary-base;
        }

        .iconfont {
          font-size: 18px;
        }
      }
    }
  }
}

.invalid {
  .body .item {
    opacity: 0.6;

    .name {
      text-decoration: line-through;
    }

    .iconfont,
    .numCon {
      color: #ccc !important;
      cursor: not-allowed;
    }
  }
}

.footer {
  position: sticky;
  bottom: 0;
  background: var(--card-bg);
  border-top: 1px solid var(--border-color);
  padding: 20px min(160px, 8vw);
  margin: 0 -min(160px, 8vw) -60px;
  box-shadow: 0 -2px 8px var(--shadow-color);
  z-index: 100;
  transition: background-color var(--transition-time), border-color var(--transition-time), box-shadow var(--transition-time);

  .num {
    font-size: 14px;
    color: var(--text-secondary);
    transition: color var(--transition-time);
  }

  .total {
    font-size: 16px;
    color: var(--text-secondary);
    margin-right: 20px;
    transition: color var(--transition-time);

    .font-color {
      font-size: 24px;
      font-weight: 700;
      color: var(--primary-base);
      transition: color var(--transition-time);
    }
  }

  .bnt {
    padding: 16px 40px;
    background: var(--primary-base);
    color: var(--button-text);
    border: none;
    border-radius: 4px;
    font-size: 16px;
    font-weight: 600;
    cursor: pointer;
    transition: all 0.3s ease;

    &:hover {
      transform: translateY(-1px);
      background: var(--primary-light);
      box-shadow: 0 4px 12px rgba(var(--primary-base-rgb), 0.3);
    }

    &:active {
      transform: translateY(0);
    }
  }
}


// 響應式設計
@media (max-width: 1200px) {
  .shoppingCart {
    padding-left: 40px;
    padding-right: 40px;
  }
}

@media (max-width: 768px) {
  .shoppingCart {
    padding: 100px 20px 60px;

    .cartList {
      .header {
        display: none;
      }

      .body .item {
        flex-direction: column;
        align-items: stretch;
        padding: 16px;

        .allSelect {
          position: absolute;
          top: 16px;
          left: 16px;
          width: auto;
          height: auto;
          padding-left: 0;
        }

        .info {
          margin: 0 0 16px 40px;
          padding: 0;

          .pictrue {
            width: 60px;
            height: 60px;
            margin-right: 12px;
          }
        }

        .price,
        .num,
        .money {
          width: auto;
          margin-bottom: 12px;
          justify-content: space-between;

          &::before {
            content: attr(data-label);
            font-weight: 600;
            color: var(--text-secondary);
            transition: color var(--transition-time);
          }
        }

        .operate {
          position: absolute;
          top: 16px;
          right: 16px;
          width: auto;
        }
      }
    }

    .footer {
      padding: 16px 20px;
      margin: 0 0 -60px;
      border-radius: 8px;
      overflow: hidden;

      .total {
        margin-right: 12px;

        .font-color {
          font-size: 20px;
        }
      }

      .bnt {
        padding: 12px 24px;
        font-size: 14px;
      }
    }
  }
}

// 複選框
.well-check {
  display: flex;
  align-items: center;
  cursor: pointer;
  line-height: 1;

  input[type="checkbox"] {
    display: none;
  }

  .icon {
    width: 16px;
    height: 16px;
    border: 2px solid var(--border-color);
    border-radius: 4px;
    margin-right: 16px;
    position: relative;
    transition: all 0.2s ease;
    flex-shrink: 0;
    background: var(--card-bg);

    &::after {
      content: '';
      position: absolute;
      left: 5px;
      top: 2px;
      width: 3px;
      height: 6px;
      border: solid var(--button-text);
      border-width: 0 2px 2px 0;
      transform: rotate(45deg);
      opacity: 0;
      transition: opacity 0.2s ease;
    }
  }

  input[type="checkbox"]:checked+.icon {
    background: var(--primary-base);
    border-color: var(--primary-base);

    &::after {
      opacity: 1;
    }
  }

  .checkAll {
    line-height: 1;
    font-size: 14px;
    color: var(--text-secondary);
    transition: color var(--transition-time);
  }
}
</style>
